defmodule EliPhxPlayWeb.DashboardLive do
  use EliPhxPlayWeb, :live_view

  alias EliPhxPlay.Context.Accounts
  alias EliPhxPlay.Context.UserRelationship
  alias EliPhxPlay.Context.Groups
  alias EliPhxPlay.Context.GroupMembers
  alias EliPhxPlayWeb.Components.DashboardRight.{RecentChatsComponent, ContactsComponent,HeaderComponent,GroupsComponent}
  def mount(_params, session, socket) do
    user_id = session["user_id"]
    user = Accounts.get_user(user_id)
    acceptednum =UserRelationship.get_accepted_relationships_count(user_id)
    pendingnum =UserRelationship.get_pending_relationships_count(user_id)
    contacts = UserRelationship.get_accepted_relationships_with_user_info(user_id)
    groups = GroupMembers.get_user_groups(user_id)
    if connected?(socket) do
      case user_id do
        nil -> :ok
        user_id -> Phoenix.PubSub.subscribe(EliPhxPlay.PubSub, "user_notifications:#{user_id}")
      end
    end



    {:ok, assign(socket,
      user_id: user_id,
      user: user,
      acceptednum: acceptednum,
      pendingnum: pendingnum,
      groups: groups,
      current_tab: "recent_chats",  # 默认显示最近聊天
      recent_chats: [],  # 待实现：获取最近聊天列表
      contacts: contacts      # 获取联系人列表
    )}
  end

  def render(assigns) do
    ~H"""
    <!-- 修改1：主容器 - 添加 overflow-hidden，移除 w-full -->
    <div class="flex h-screen bg-gray-100 overflow-hidden">
      <!-- 修改2：左侧边栏 - 改为 h-full，添加 flex-shrink-0 -->
      <%!-- w-80 bg-white shadow-lg flex flex-col h-full flex-shrink-0 --%>
      <div class="w-16 md:w-80 bg-[#f8fafc] shadow-lg flex flex-col h-full flex-shrink-0">
        <!-- 修改3：用户信息区域 - 添加 flex-shrink-0 -->
        <div class="p-2 md:p-6 border-b border-gray-200 flex-shrink-0">
          <div class="flex flex-col items-center">
            <!-- 用户头像 -->
            <div class="w-12 h-12 md:w-16 md:h-16 rounded-full bg-gradient-to-r from-blue-500 to-purple-600 flex items-center justify-center text-white text-lg md:text-xl font-bold mb-1 md:mb-3">
              <%= if @user && @user.avatar_url do %>
                <img src={@user.avatar_url} alt="头像" class="w-16 h-16 rounded-full object-cover" />
              <% else %>
                <%= if @user && @user.nickname do %>
                  <%= String.first(@user.nickname) %>
                <% else %>
                  👤
                <% end %>
              <% end %>
            </div>
            <!-- 用户名 - 手机端隐藏 -->
            <h2 class="hidden md:block text-lg font-semibold text-gray-800 mb-1">
              <%= if @user, do: @user.nickname || "用户", else: "未登录用户" %>
            </h2>
            <!-- 在线状态 - 手机端隐藏 -->
            <div class="hidden md:flex items-center text-sm text-gray-500">
              <div class="w-2 h-2 bg-green-400 rounded-full mr-2"></div>
              在线
            </div>

          </div>
        </div>

        <!-- 导航按钮区域 -->
        <div class="flex-1 p-1 md:p-4 overflow-y-auto">
          <nav class="space-y-2">
            <!-- 最近聊天按钮 -->
          <button
            phx-click="switch_tab"
            phx-value-tab="recent_chats"
            class={"w-full flex items-center justify-center md:justify-start px-2 md:px-4 py-3 rounded-lg text-left transition-colors #{if @current_tab == "recent_chats", do: "bg-blue-50 text-blue-700 border border-blue-200", else: "hover:bg-gray-50 text-gray-700"}"}
          >
            <svg class="w-5 h-5 md:mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
            </svg>
            <span class="hidden md:inline">最近聊天</span>
            <%= if length(@recent_chats) > 0 do %>
              <span class="hidden md:inline ml-auto bg-blue-500 text-white text-xs rounded-full px-2 py-1">
                <%= length(@recent_chats) %>
              </span>
            <% end %>
          </button>


          <button
            phx-click="switch_tab"
            phx-value-tab="contacts"
            class={"w-full flex items-center justify-center md:justify-start px-2 md:px-4 py-3 rounded-lg text-left transition-colors #{if @current_tab == "contacts", do: "bg-blue-50 text-blue-700 border border-blue-200", else: "hover:bg-gray-50 text-gray-700"}"}
          >
            <div class="relative">
              <svg class="w-5 h-5 md:mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
              </svg>
              <%= if @pendingnum > 0 do %>
                <div class="absolute -top-1 right-0 md:-right w-2 h-2 bg-red-500 rounded-full"></div>
              <% end %>
            </div>
            <span class="hidden md:inline">联系人</span>
            <%= if length(@contacts) > 0 do %>
              <span class="hidden md:inline ml-auto text-gray-400 text-sm">
                <%= length(@contacts) %>
              </span>
            <% end %>
          </button>

          <button
            phx-click="switch_tab"
            phx-value-tab="groups"
            class={"w-full flex items-center justify-center md:justify-start px-2 md:px-4 py-3 rounded-lg text-left transition-colors #{if @current_tab == "groups", do: "bg-blue-50 text-blue-700 border border-blue-200", else: "hover:bg-gray-50 text-gray-700"}"}
          >

<svg class="w-5 h-5 md:mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 4v-4z"/>
</svg>
            <span class="hidden md:inline">群聊</span>
            <%= if @groups && length(@groups) > 0 do %>
              <span class="hidden md:inline ml-auto text-gray-400 text-sm">
                <%= length(@groups) %>
              </span>
            <% end %>
          </button>





          </nav>
        </div>

        <!-- 修改4：底部设置区域 - 添加 flex-shrink-0 -->
        <div class="p-2 md:p-4 border-t border-gray-200 flex-shrink-0">
          <button class="w-full flex items-center justify-center md:justify-start px-2 md:px-4 py-2 text-gray-600 hover:bg-gray-50 rounded-lg transition-colors">
          <svg class="w-5 h-5 md:mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
          </svg>
          <span class="hidden md:inline">设置</span>

          </button>
        </div>
      </div>
      <!-- 右侧内容区域 -->
      <div class="flex-1 flex flex-col h-full overflow-hidden">
        <!-- 使用统一标题栏组件 -->
        <%!-- <.live_component
          module={HeaderComponent}
          id="header"
          user_id={@user_id}
          page_type={get_page_type(@current_tab)}
          data={get_page_data(@current_tab, assigns)}
          title={get_page_title(@current_tab)}
        /> --%>

        <!-- 内容区域 -->
        <div class="flex-1 overflow-hidden">
          <%= case @current_tab do %>
            <% "recent_chats" -> %>
              <.live_component
                module={RecentChatsComponent}
                id="recent-chats"
                user_id={@user_id}
                recent_chats={@recent_chats}
              />
            <% "contacts" -> %>
              <.live_component
                module={ContactsComponent}
                id="contacts"
                user_id={@user_id}
                acceptednum={@acceptednum}
                pendingnum={@pendingnum}
                contacts={@contacts}
              />

            <% "groups" -> %>
              <.live_component
                module={GroupsComponent}
                id="groups"
                user_id={@user_id}
                groups={@groups}
              />
            <% _ -> %>
              <.live_component
                module={RecentChatsComponent}
                id="recent-chats-default"
                user_id={@user_id}
                recent_chats={@recent_chats}
              />
          <% end %>
        </div>
      </div>



    </div>
    """
  end

  def handle_event("switch_tab", %{"tab" => tab}, socket) do
    {:noreply, assign(socket, current_tab: tab)}
  end



  # 获取页面类型
defp get_page_type(current_tab) do
  case current_tab do
    "recent_chats" -> :recent_chats
    "contacts" -> :contacts
    "settings" -> :settings
    "groups" -> :groups
    _ -> :default
  end
end

# 获取页面数据
defp get_page_data(current_tab, assigns) do
  case current_tab do
    "recent_chats" -> assigns.recent_chats
    "contacts" -> assigns.contacts
    "groups" -> assigns.groups
    _ -> []
  end
end

# 获取页面标题
defp get_page_title(current_tab) do
  case current_tab do
    "recent_chats" -> "最近聊天"
    "contacts" -> "联系人"
    "groups" -> "群聊"
    "settings" -> "设置"
    _ -> "仪表板"
  end
end

# 处理来自标题栏组件的消息
def handle_info({:search, search_term}, socket) do
  # 处理搜索逻辑
  {:noreply, socket}
end

def handle_info(:add_friend, socket) do
  # 处理添加好友逻辑
  {:noreply, socket}
end

def handle_info(:new_chat, socket) do
  # 处理新建聊天逻辑
  {:noreply, socket}
end

def handle_info(:save_settings, socket) do
  # 处理保存设置逻辑
  {:noreply, socket}
end

def handle_info({:update_pending_count, new_count}, socket) do
  {:noreply, assign(socket, pendingnum: new_count)}
end


# 处理新的好友请求通知
def handle_info({:new_friend_request, %{from_user_id: from_user_id, relationship_id: _relationship_id}}, socket) do
  current_user_id = socket.assigns.user_id

  # 重新计算待处理请求数量
  pending_count = UserRelationship.get_pending_relationships_count(current_user_id)

  # 获取发送方用户信息用于通知
  sender_info = case Accounts.get_user(from_user_id) do
    %{nickname: nickname} when nickname != nil -> nickname
    %{account: account} -> account
    _ -> "某用户"
  end

  {:noreply, assign(socket, pendingnum: pending_count)}
end



  # 只在特定事件后更新
  def handle_info({:update_contacts}, socket) do
    contacts = UserRelationship.get_accepted_relationships_with_user_info(socket.assigns.user_id)
    acceptednum = UserRelationship.get_accepted_relationships_count(socket.assigns.user_id)
    {:noreply, assign(socket,
      contacts: contacts,
      acceptednum: acceptednum
      )}
  end

  # 处理好友请求被接受的通知
  def handle_info({:friend_request_accepted, %{accepted_by_user_id: accepted_by_user_id}}, socket) do
    current_user_id = socket.assigns.user_id

    # 重新获取联系人列表（现在应该包含新的好友）
    contacts = UserRelationship.get_accepted_relationships_with_user_info(current_user_id)
    acceptednum = UserRelationship.get_accepted_relationships_count(current_user_id)

    # 获取接受方用户信息用于通知（可选）
    accepter_info = case Accounts.get_user(accepted_by_user_id) do
      %{nickname: nickname} when nickname != nil -> nickname
      %{account: account} -> account
      _ -> "某用户"
    end

    {:noreply, assign(socket,
      contacts: contacts,
      acceptednum: acceptednum
    )}
  end


  # 处理群聊列表更新
  def handle_info({:update_groups}, socket) do
    user_id = socket.assigns.user_id
    groups = GroupMembers.get_user_groups(user_id)
    {:noreply, assign(socket, groups: groups)}
  end



end
